//
//  CityViewController.m
//  WhereToTravel
//
//  Created by dlios on 15/10/16.
//  Copyright © 2015年 zhoushengmin. All rights reserved.
//

#import "CityViewController.h"
#import "CountryModel.h"
#import "DiscountCell.h"
#import "HotCollectCell.h"
#import "ButtonCell.h"
#import "SDCycleScrollView.h"
#import "DisCountWebView.h"
#import "AllDiscountViewController.h"
#import "SuperWebViewViewController.h"
#import "CapsuleViewController.h"
#import "PlayViewController.h"
#import "FoodViewController.h"
#import "HotelViewController.h"
#import "City.h"
#import "CoreDataManager.h"

@interface CityViewController ()<UITableViewDataSource,UITableViewDelegate,HotCollectCellDelegate,ButtonCellDelegate,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>
@property (nonatomic, strong)NSMutableArray *cityArr;
@property (nonatomic, strong)NSMutableArray *picArr;
@property (nonatomic, strong)UITableView *bigTable;
@property (nonatomic, strong)UIView *headView;
@property (nonatomic, strong)SDCycleScrollView *picView;
@property (nonatomic, strong)UILabel *topLabel;
@property (nonatomic, strong)UILabel *cnLabel;
@property (nonatomic, strong)UILabel *enLabel;
@property (nonatomic, strong)UIButton *rightButton;
@property (nonatomic, strong)NSMutableArray *localArr;
@property (nonatomic, strong)NSMutableArray *disArr;
@property (nonatomic, strong)NSDictionary *ccDic;
@property (nonatomic, strong)UIImageView *lineImage;
@property (nonatomic, strong)UIButton *collectionButton;
@property (nonatomic, strong)CoreDataManager *manager;

@end

@implementation CityViewController

// 视图的出现将tabbar隐藏
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeSelect) name:@"shoucang" object:nil];
}

- (void)creatData {
    NSString *str = [NSString stringWithFormat:@"http://open.qyer.com/qyer/footprint/city_detail?client_id=qyer_android&client_secret=9fcaae8aefc4f9ac4915&v=1&track_deviceid=863151025525517&track_app_version=6.7.1&track_app_channel=baidu&track_device_info=mx3&track_os=Android4.4.4&app_installtime=1444613810999&lat=38.876204&lon=121.560561&city_id=%@",self.cityId];
   
    [ZSMAFNetWork geturl:str body:nil result:ZSMJSON headerFile:nil success:^(id result) {
        self.picArr = [NSMutableArray array];
        self.ccDic = result[@"data"];
        CountryModel *pic = [[CountryModel alloc]initWithDic:self.ccDic];
        
        self.picArr = pic.photos;
       
        [self creatTableView];
        self.topLabel.text = pic.entryCont;
        self.cnLabel.text = pic.cnname;
        self.enLabel.text = pic.enname;
        
        self.localArr = [NSMutableArray array];
        self.disArr = [NSMutableArray array];
        NSArray *loArr = (NSArray *)pic.local_discount;
        NSArray *neArr = result[@"data"][@"new_discount"];
        for (NSDictionary *dic in loArr) {
            CountryModel *loModel = [[CountryModel alloc]initWithDic:dic];
            [self.localArr addObject:loModel];
        }
        for (NSDictionary *dic in neArr) {
            CountryModel *neModel = [[CountryModel alloc]initWithDic:dic];
            [self.disArr addObject:neModel];
        }
        [self.bigTable reloadData];
        self.hud.hidden = YES;
    } failure:^(NSError *error) {
        
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeSelect) name:@"shoucang" object:nil];
    self.manager = [CoreDataManager shareCoreDataManager];
    NSString *strId = [NSString stringWithFormat:@"cityId = '%@'",self.cityId];
    self.isSelect = [self.manager sendId:strId];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(night) name:@"night" object:nil];
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self.hud hide:YES afterDelay:4];
    

    [self creatData];
    NSLog(@"%@",[self.manager applicationDocumentsDirectory]);
    
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:nil];
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 左上角返回图标
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"返回"] style:(UIBarButtonItemStylePlain) target:self action:@selector(leftAction:)];
}

// 返回
- (void)leftAction:(UIBarButtonItem *)barButton {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)creatTableView {
     
    self.bigTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH * 375, HEIGHT * 603) style:UITableViewStyleGrouped];
    [self.view addSubview:self.bigTable];
   
    self.bigTable.delegate = self;
    self.bigTable.dataSource = self;
    [self creatHeadView];
    self.bigTable.tableHeaderView = self.headView;
    self.bigTable.emptyDataSetSource = self;
    self.bigTable.emptyDataSetDelegate = self;
 
    self.hud = [MBProgressHUD showHUDAddedTo:self.bigTable animated:YES];
    [self.bigTable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.equalTo(self.view);
    }];

}
// 空白页占位图
- (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView {
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(20, self.view.bounds.size.height/2, WIDTH*375, 30)];
    label.text = @"! 网速不给力";
    label.textAlignment = NSTextAlignmentCenter ;
    label.textColor = [UIColor redColor];
    return label;
}

// 触发通知方法,此时收藏的已删除,图标得改回来
- (void)changeSelect {
    self.isSelect = NO;
    [self.collectionButton  setBackgroundImage:[UIImage imageNamed:@"shoucang"] forState:UIControlStateNormal];
}
- (void)creatHeadView {
    
    self.headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH * 375, HEIGHT * 300)];

    self.headView.backgroundColor = [UIColor whiteColor];
  // 轮播图三方

    self.headView.backgroundColor = [UIColor clearColor];
  

    self.picView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, WIDTH * 375, HEIGHT * 200) imageURLStringsGroup:self.picArr];
    [self.headView addSubview:self.picView];

    self.topLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, HEIGHT * 200, WIDTH * 355, HEIGHT * 60)];
    self.lineImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, HEIGHT * 300, WIDTH * 375, HEIGHT * 1)];
    [self.lineImage setImage:[UIImage imageNamed:@"best_line"]];
    self.topLabel.textColor = [UIColor colorWithWhite:0.380 alpha:1.000];
    self.topLabel.font = [UIFont systemFontOfSize:13];
    self.topLabel.numberOfLines = 0;
    self.cnLabel = [[UILabel alloc]initWithFrame:CGRectMake(25, HEIGHT * 140, WIDTH * 375, HEIGHT * 20)];
    self.cnLabel.textColor = [UIColor whiteColor];
    self.cnLabel.font = [UIFont boldSystemFontOfSize:15];
    self.enLabel = [[UILabel alloc]initWithFrame:CGRectMake(25, HEIGHT * 160, WIDTH * 375, HEIGHT * 20)];
    self.enLabel.textColor = [UIColor whiteColor];
    self.enLabel.font = [UIFont boldSystemFontOfSize:15];
    self.collectionButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.collectionButton.frame = CGRectMake(WIDTH * 320, HEIGHT * 25, WIDTH * 50, HEIGHT * 50);
    
    if (self.isSelect == YES) {
        [self.collectionButton  setBackgroundImage:[UIImage imageNamed:@"shoucang_b"] forState:UIControlStateNormal];
    }else if (self.isSelect == NO) {
        [self.collectionButton  setBackgroundImage:[UIImage imageNamed:@"shoucang"] forState:UIControlStateNormal];
    }
    if (self.picArr.count == 0) {
        self.collectionButton.userInteractionEnabled  = NO;
    }
    
    [self.collectionButton addTarget:self action:@selector(collectionSender:) forControlEvents:UIControlEventTouchUpInside];
    [self.headView addSubview:self.collectionButton];
    [self.headView addSubview:self.topLabel];
    [self.headView addSubview:self.cnLabel];
    [self.headView addSubview:self.enLabel];
    [self.headView addSubview:self.lineImage];
    self.rightButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.rightButton.frame = CGRectMake(WIDTH * 270, HEIGHT * 270, WIDTH * 100, HEIGHT * 10);
    [self.rightButton setTitle:@"城市实用信息 >" forState:UIControlStateNormal];
    self.rightButton.tintColor = [UIColor colorWithRed:0.071 green:0.600 blue:0.049 alpha:1.000];
    self.rightButton.titleLabel.font = [UIFont systemFontOfSize:12];
    [self.rightButton addTarget:self action:@selector(pushButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.headView addSubview:self.rightButton];
    
}
// 收藏
- (void)collectionSender:(UIButton *)sender {
    // 未收藏
    if (self.isSelect == NO) {
        City *city = [NSEntityDescription insertNewObjectForEntityForName:@"City" inManagedObjectContext:self.manager.managedObjectContext];
        city.cityId = self.cityId;
        city.photo = self.picArr[0];
        city.placeName = self.ccDic[@"cnname"];
        [self.manager saveContext];
        self.isSelect = !self.isSelect;
        [self.collectionButton setBackgroundImage:[UIImage imageNamed:@"shoucang_b"] forState:UIControlStateNormal];
        // 取消收藏
    }else if (self.isSelect == YES) {
        // 通过Id条件查询
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"City" inManagedObjectContext:self.manager.managedObjectContext];
        NSFetchRequest *request = [[NSFetchRequest alloc]init];
        [request setEntity:entity];
        // 构造查询条件,相当于where语句
        NSString * strId = [NSString stringWithFormat:@"cityId = '%@'",self.cityId];
        NSPredicate *predicate = [NSPredicate predicateWithFormat:strId];
        // 把查询条件放进去
        [request setPredicate:predicate];
        // 执行查询
        NSManagedObject *city = [[self.manager.managedObjectContext executeFetchRequest:request error:nil]lastObject];
        //删除之后保存到数据库
        if (city) {
             [self.manager.managedObjectContext deleteObject:city];
            [self.manager saveContext];
        }
       
        
        self.isSelect = !self.isSelect;
        [self.collectionButton setBackgroundImage:[UIImage imageNamed:@"shoucang"] forState:UIControlStateNormal];
    }
    
    
}
- (void)pushButton:(UIButton *)button {
    SuperWebViewViewController *web = [[SuperWebViewViewController alloc]init];
    web.cityId = self.cityId;
    [self.navigationController pushViewController:web animated:YES];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }else if (section == 1) {
        return 1;
    }else {
        return self.disArr.count;
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0&&indexPath.section == 0) {
        return HEIGHT * 100;
    }else if (indexPath.section == 1 && self.localArr.count != 0) {
        return HEIGHT * 230;
    }else if (indexPath.section == 2 && self.disArr.count != 0) {
          return HEIGHT * 100;
    }
    return 0;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, HEIGHT *-20, WIDTH * 375, HEIGHT * 50)];
    view.backgroundColor = [UIColor whiteColor];
    
    UILabel *sectLabel = [[UILabel alloc]initWithFrame:CGRectMake(WIDTH * 10, HEIGHT * 20, WIDTH * 100, HEIGHT * 20)];
    [view addSubview:sectLabel];
   
     if (section == 1&&self.localArr.count!=0) {
        sectLabel.text = @"精彩当地游";
     }else if (section == 2&&self.disArr.count!=0) {
         sectLabel.text = @"超值自由行";
     }    if (self.localArr.count>=4&&section == 1) {
        UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeSystem];
        rightButton.tag = 1000;
        rightButton.frame = CGRectMake(WIDTH * 270, HEIGHT * 20, WIDTH * 100, HEIGHT * 20);
        [rightButton setTitle:@"查看全部" forState:UIControlStateNormal];
        [rightButton addTarget:self action:@selector(rightClick:) forControlEvents:UIControlEventTouchUpInside];
        rightButton.tintColor = [UIColor colorWithRed:0.071 green:0.600 blue:0.049 alpha:1.000];
        [view addSubview:rightButton];
        
        
    }else if (self.disArr.count>=5&&section ==2) {
        UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeSystem];
        rightButton.tag = 1001;
        rightButton.frame = CGRectMake(WIDTH * 270, HEIGHT * 20, WIDTH * 100, HEIGHT * 20);
        [rightButton setTitle:@"查看全部" forState:UIControlStateNormal];
        [rightButton addTarget:self action:@selector(rightClick:) forControlEvents:UIControlEventTouchUpInside];
        rightButton.tintColor = [UIColor colorWithRed:0.071 green:0.600 blue:0.049 alpha:1.000];
        [view addSubview:rightButton];
    
    }
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (self.localArr.count == 0&&section == 1) {
        return 0;
    }else if (self.disArr.count == 0&&section == 2) {
        return 0;
    }else if (section == 0) {
        return 0;
    }
    return HEIGHT * 50;
    
}
- (void)rightClick:(UIButton *)button {
    if (button.tag == 1000) {
        AllDiscountViewController *allDisV = [[AllDiscountViewController alloc]init];
        allDisV.allDiscount = self.cityId;
        allDisV.type = @"2";
        allDisV.select = 1;
        allDisV.placeName = self.ccDic[@"cnname"];
        [self.navigationController pushViewController:allDisV animated:YES];
    }else if (button.tag == 1001) {
        AllDiscountViewController *allDisV = [[AllDiscountViewController alloc]init];
        allDisV.allDiscount = self.cityId;
        allDisV.select = 0;
          allDisV.type = @"2";
        allDisV.placeName = self.ccDic[@"cnname"];
        [self.navigationController pushViewController:allDisV animated:YES];
    }

    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 2) {
        static NSString *reuse = @"tabCell";
        DiscountCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
        if (!cell) {
            cell = [[DiscountCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse];
            cell.backgroundColor = [UIColor clearColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        CountryModel *disModel = self.disArr[indexPath.row];
        [cell.leftImage sd_setImageWithURL:[NSURL URLWithString:disModel.photo] placeholderImage:[UIImage imageNamed:@"F"]];
        cell.topLabel.text = disModel.title;
        cell.leftLabel.text = disModel.priceoff;
        NSString *str = [[disModel.price stringByReplacingOccurrencesOfString:@"<em>" withString:@""]stringByReplacingOccurrencesOfString:@"</em>元起" withString:@""];
          cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.numberLabel.text = str ;
        cell.rightLabel.text = @"元起";
        return cell;

    }else if (indexPath.section == 1) {
        static NSString *reuse = @"hotCell";
        HotCollectCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
        if (!cell) {
            cell = [[HotCollectCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse];
            cell.backgroundColor = [UIColor clearColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        cell.delegate = self;
        cell.hotArr = self.localArr;
        [cell.collect reloadData];
        
        return cell;
    }else {
        static NSString *reuse = @"buttCell";
        ButtonCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
        if (!cell) {
            cell = [[ButtonCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse];
            cell.backgroundColor = [UIColor clearColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        cell.delegate = self;
        return cell;
    }
}
- (void)give:(NSInteger)sd {
    if (sd == 0) {
        CapsuleViewController *caVC = [[CapsuleViewController alloc]init];
        NSString *str = [NSString stringWithFormat:@"http://open.qyer.com/qyer/footprint/mguide_list?client_id=qyer_android&client_secret=9fcaae8aefc4f9ac4915&v=1&track_deviceid=863151025525517&track_app_version=6.7.1&track_app_channel=baidu&track_device_info=mx3&track_os=Android4.4.4&app_installtime=1444613810999&lat=38.876204&lon=121.560561&type=city&id=%@&count=20&page=1",self.cityId];
        caVC.url = str;
         [self.navigationController pushViewController:caVC animated:YES];

    }else if (sd == 1) {
        PlayViewController *plVC = [[PlayViewController alloc]init];
        NSString *str = [NSString stringWithFormat:@"http://open.qyer.com/qyer/onroad/poi_list?client_id=qyer_android&client_secret=9fcaae8aefc4f9ac4915&v=1&track_deviceid=863151025525517&track_app_version=6.7.1&track_app_channel=baidu&track_device_info=mx3&track_os=Android4.4.4&app_installtime=1444613810999&page=1&city_id=%@&category_id=32,147,148&count=20&orderby=popular",self.cityId];
        plVC.pUrl = str;
        [self.navigationController pushViewController:plVC animated:YES];
    }else if (sd == 2) {
        FoodViewController *fVC = [[FoodViewController alloc]init];
        NSString *str = [NSString stringWithFormat:@"http://open.qyer.com/qyer/onroad/poi_list?client_id=qyer_android&client_secret=9fcaae8aefc4f9ac4915&v=1&track_deviceid=863151025525517&track_app_version=6.7.1&track_app_channel=baidu&track_device_info=mx3&track_os=Android4.4.4&app_installtime=1444613810999&page=1&city_id=%@&category_id=78&count=20&orderby=popular",self.cityId];
        fVC.fUrl = str;
        [self.navigationController pushViewController:fVC animated:YES];
    }else {
        HotelViewController *hVC = [[HotelViewController alloc]init];
        NSString *str = [NSString stringWithFormat:@" http://open.qyer.com/qyer/hotel/search_list?client_id=qyer_android&client_secret=9fcaae8aefc4f9ac4915&v=1&track_deviceid=863151025525517&track_app_version=6.7.1&track_app_channel=baidu&track_device_info=mx3&track_os=Android4.4.4&app_installtime=1444613810999&lat=38.883443&lon=121.544998&city_id=%@&checkin=2015-11-16&checkout=2015-11-17&from_key=app_android_list&count=10&orderby=0&page=1",self.cityId];
      
        hVC.hUrl = str;
        [self.navigationController pushViewController:hVC animated:YES];
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
       [self.bigTable deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 2) {
        DisCountWebView *web = [[DisCountWebView alloc]init];
        CountryModel *disModel = self.disArr[indexPath.row];
        web.disCountStr = [NSString stringWithFormat:@"http://m.qyer.com/z/deal/%@/?source=app&client_id=qyer_ios&track_app_version=6.6&track_deviceid=5B302CA5-E537-4B10-955D-520F4C91BAFE&track_user_id=6654242%%20",disModel.uId];
        [self.navigationController pushViewController:web animated:YES];
        
    }
    
    
}
- (void)send:(NSString *)cityNum {
    DisCountWebView *web = [[DisCountWebView alloc]init];
        NSString *str = [NSString stringWithFormat:@"http://m.qyer.com/z/deal/%@/?source=app&client_id=qyer_ios&track_app_version=6.6&track_deviceid=5B302CA5-E537-4B10-955D-520F4C91BAFE&track_user_id=6654242%%20",cityNum];
    web.localStr = str;
   
    [self.navigationController pushViewController:web animated:YES];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"reload" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"night" object:nil];
    
}



- (void)night {
    if ([SingletonNight shareSingletonNight].isSelete == YES) {
        self.bigTable.backgroundColor = [UIColor blackColor];
        self.topLabel.textColor = [UIColor whiteColor];
    }
    else {
        self.bigTable.backgroundColor = [UIColor whiteColor];
        self.topLabel.textColor = [UIColor colorWithWhite:0.380 alpha:1.000];
    }
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
